package com.demo.server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 基于BIO实现的网络聊天室服务器； 每一个请求对应一个线程。
 * 
 * @author shaoyuxia
 *
 */
class ChatServer extends AbstractChatServer<BufferedWriter> {

	private static final Log LOG = LogFactory.getLog(ChatServer.class);

	public ChatServer(int port) {
		super(port);
	}

	public ChatServer(int port, int backlog) {
		super(port, backlog);
	}

	@Override
	public void bootStrap() throws Exception {
		LOG.debug("server start");
		try {
			serverSocket = new ServerSocket(port, backlog);
		} catch (IOException e1) {
			System.exit(0);
		}
		showMsg("server start...");
		while (true) {
			Socket socket = serverSocket.accept();
			handleConnection(socket);
		}
	}

	protected void handleSingleConnection(Socket socket) {
		LOG.debug("Handle connection from " + socket.getInetAddress() + ":" + socket.getPort());
		String nickName = null;
		try (BufferedReader reader = new BufferedReader(
				new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
				BufferedWriter writer = new BufferedWriter(
						new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));) {
			// get nick name
			while ((nickName = reader.readLine()) != null) {
				nickName = nickName.trim();
				LOG.debug("get Nick name:" + nickName);
				if (!isNickNameExisted(nickName)) {
					chatterMap.put(nickName.trim(), writer);
					sendLine(NICKNAMEW_VALID, writer);
					sendToAll("[system notification]:“" + nickName + "”已上线;当前在线人数:" + chatterMap.size());
					break;
				}
				sendLine(NICKNAMEW_NOT_VALID, writer);
			}
			// start chat
			String msg = null;
			while ((msg = reader.readLine()) != null) {
				LOG.debug(nickName + ":" + msg);
				if (msg.equals(DISCONNECT)) {
					chatterMap.remove(nickName);
					sendToAll("[system notification]:“" + nickName + "”已离线;当前在线人数:" + getOnlineCount());
					socket.close();
					break;
				}
				if (msg.startsWith("@")) {
					String name = msg.substring(1).split(" ")[0];
					sendToPrivate(wrapMsg(nickName, msg), name);
				} else {
					sendToAll(wrapMsg(nickName, msg));
				}
			}

		} catch (Exception e) {
			if (chatterMap.get(nickName) != null)
				chatterMap.remove(nickName);
			sendToAll("[system notification]:“" + nickName + " 已离线;当前在线人数:" + getOnlineCount());
			if (!socket.isClosed())
				e.printStackTrace();
			else {
				try {
					socket.close();
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	private void sendLine(String msg, BufferedWriter writer) {
		try {
			if (writer != null) {
				writer.write(msg + "\n");
				writer.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@Override
	protected void sendToAll(String msg) {
		chatterMap.forEachValue(10, w -> {
			if (w != null) {
				sendLine(msg, w);
			}
		});
	}

	@Override
	protected void sendToPrivate(String msg, String nickName) {
		sendLine(msg, chatterMap.get(nickName));

	}

	protected void handleConnection(Socket connection) {
		// create a new thread for every connection
		new Thread(() -> {
			LOG.debug("create a new thread:" + Thread.currentThread().getName());
			handleSingleConnection(connection);
		}).start();
	}

	private String wrapMsg(String nickName, String msg) {
		return nickName + ":" + msg + " @" + new Date();
	}

}
